<template>
  <div class="setting">
    <h2>课程资料管理</h2>
    <div class="flex-center">
      
      <el-button type="success" size="mini" @click="addCourse"
        >添加课程资料</el-button
      >
      <el-input
        v-model="key"
        size="mini"
        style="width: 120px"
        placeholder="关键字/词查询"
      ></el-input>
      <el-button
        class="ml0"
        size="mini"
        type="primary"
        @click="refreshTable(true)"
        >查询</el-button
      >
    </div>

    <div class="consultation-block">
      <div class="table">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="课程名称"> </el-table-column>
          <el-table-column prop="user.nickname" label="教师"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                @click="updateCourse(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteCourse(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="refreshTable"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="添加课程资料"
      :visible.sync="isVisible"
      :close-on-click-modal="false"
      width="70%"
      :before-close="handleAddClose"
    >
      <el-form
        :model="addForm"
        status-icon
        :rules="rules"
        size="mini"
        ref="addForm"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input :min="0" type="text" v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="教师" prop="userId">
          <el-select v-model="addForm.userId" placeholder="请选择">
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="addForm.type == '课程资料' ? 'PDF文件' : '教学视频'" prop="fileList">
          <el-upload
            class="avatar-uploader"
            ref="upload"
            :action="'/upload'"
            :file-list="addForm.fileList"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
          >
            <i
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
          
        </el-form-item>
        <!-- <el-form-item label="课程介绍">
          <vue-editor
            :editorOptions="editorOption"
            v-model="addForm.content"
            useCustomImageHandler
            @image-added="handleImageAdded"
          />
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCourse,
  addCourse,
  updateCourse,
  deleteCourse,
  getUser,
} from "../service.js";
import { VueEditor } from "vue2-editor";

export default {
  components: { VueEditor },
  data() {
    return {
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            // ['blockquote', 'code-block'], //引用，代码块
            // [{'header': 1}, {'header': 2}], // 标题，键值对的形式；1、2表示字体大小
            // [{'list': 'ordered'}, {'list': 'bullet'}], //列表
            // [{'script': 'sub'}, {'script': 'super'}], // 上下标
            // [{'indent': '-1'}, {'indent': '+1'}], // 缩进
            // [{'direction': 'rtl'}], // 文本方向
            // [{ size: ["small", false, "large", "huge"] }], // 字体大小
            // [{'header': [1, 2, 3, 4, 5, 6, false]}], //几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            // [{'font': []}], //字体
            [{ align: [] }], //对齐方式
            ["clean"], //清除字体样式
            ['image'] //上传图片
          ],
        },
        placeholder: "输入内容...",
      },
      tableData: [],
      isVisible: false,
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        userId: [{ required: true, message: "请输入", trigger: "blur" }],
        fileList: [{ required: true, message: "请上传", trigger: "blur" }],
        type: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      teacherList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      addForm: {
        fileList: []
      },
      map: null,
      userId: '',
      typeList: ['课程资料', '教学视频'],
      key: ''
    };
  },
  mounted() {
    this.refreshTable();
    getUser({
      page: 1,
      pageSize: 1111,
      role: '教师'
    }).then((res) => {
      this.teacherList = res.data.data;
    });
  },
  methods: {
    handleAddClose() {
      this.isVisible = false;
    },
    addCourse() {
      this.addForm = {
        name: "",
        content: "",
        fileList: [],
        userId: "",
        type: '课程资料'
      };
      this.isVisible = true;
      this.$nextTick(() => {
        this.$refs.upload.clearFiles()
      })
    },
    handleAvatarSuccess(info) {
      this.addForm.fileList.push(info)
    },
    refreshTable(init = false) {
      if (init) {
        this.currentPage = 1;
      }
      let params = {
        page: this.currentPage,
        pageSize: this.pageSize,
      }
      if (this.key) {
        params.key = this.key
      }
      getCourse(params).then((res) => {
        this.tableData = res.data.data;
        this.total = res.data.total;
      });
    },
    updateCourse(row) {
      this.addForm = JSON.parse(JSON.stringify(row));
      this.addForm.fileList = JSON.parse(this.addForm.fileList)
      this.isVisible = true;
    },
    handleRemove(val) {
      let filename = val.response.url
      let index = this.addForm.fileList.findIndex(v => v.url == filename)
      if (index >= 0) {
        this.addForm.fileList.splice(index, 1)
      }
    },
    submitForm(formName) {
      if (this.addForm.type == '课程资料') {
        let flag = this.addForm.fileList.length == this.addForm.fileList.filter(v => v.name.includes('.pdf')).length
        if (!flag) {
          this.$message.error('课程资料只支持.pdf文件')
          return
        }
      }

      if (this.addForm.type == '教学视频') {
        let flag = this.addForm.fileList.length == this.addForm.fileList.filter(v => v.name.includes('.mp4')).length
        if (!flag) {
          this.$message.error('教学视频只支持.mp4文件')
          return
        }
      }
     
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.addForm.id) {
            updateCourse(this.addForm.id, {
              ...this.addForm,
              fileList: JSON.stringify(this.addForm.fileList)
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.isVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else {
            addCourse({
              ...this.addForm,
              fileList: JSON.stringify(this.addForm.fileList)
            }).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.isVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    },
    deleteCourse(row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteCourse(row.id).then((res) => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.isVisible = false;
            this.refreshTable();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 处理富文本编辑框的图片
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      var xhr = new XMLHttpRequest();
      xhr.open("post", "http://localhost:3000/upload");
      xhr.send(formData);
      xhr.onload = function () {
        if (xhr.status == 200) {
          let res = JSON.parse(xhr.responseText);
          const url = "http://localhost:3000/" + res.url;
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        }
      };
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
#map {
  width: 100%;
  height: 600px;
}
</style>
